package net.jsoft.platform.security.config.WebSecurity;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;
import net.jsoft.platform.security.util.MD5Util;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider
{

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private UserRepository repository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        String pwd = MD5Util.getMd5(name + password);

        logger.info("Name = " + name + " ,Password = " + pwd);

        // use the credentials and authenticate against the third-party system
        SysUser user = repository.findByName(name);
        if (user != null && user.getPassword().equalsIgnoreCase(pwd))
        {
            logger.info("Succesful authentication!");
            return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
        }

        logger.info("Login fail!");

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication)
    {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
